using CoreManager.Core.Caching;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using System;

namespace CoreManager.Core.Extensions
{
    /// <summary>
    /// 缓存服务扩展方法
    /// </summary>
    public static class CacheServiceExtensions
    {
        /// <summary>
        /// 添加缓存服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddCacheService(this IServiceCollection services, IConfiguration configuration)
        {
            // 注册缓存选项
            services.Configure<CacheOptions>(configuration.GetSection("Cache"));
            
            // 获取缓存配置
            var cacheOptions = new CacheOptions();
            configuration.GetSection("Cache").Bind(cacheOptions);

            // 添加内存缓存
            services.AddMemoryCache();

            // 根据配置选择缓存实现
            if (cacheOptions.CacheType == CacheType.Redis)
            {
                // 注册Redis连接
                services.AddSingleton<ConnectionMultiplexer>(sp => ConnectionMultiplexer.Connect(cacheOptions.RedisConnectionString));
                // 注册Redis缓存服务
                services.AddSingleton<ICacheService, RedisCacheService>();
            }
            else
            {
                // 注册内存缓存服务
                services.AddSingleton<ICacheService, MemoryCacheService>();
            }

            return services;
        }
    }
}